<?php


namespace App\Service\OpenShop\Feishu;


use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel as ManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel as MappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Service\OpenShop\Organization\WarZoneService;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrganizationManageService extends BaseService
{
    public static function getOrganizationInfoById($manageId)
    {
        $info = ManageModel::getOrganizationInfoById($manageId);
        if ($info) {
            $info              = $info->toArray();
            $info['regionRel'] = $info['region_rel'];
            unset($info['region_rel']);
            $info["operationAttacheUser"] = $info["operationAttacheUser"] == "null" ? [] : json_decode($info["operationAttacheUser"],
                true);
            $info["attendanceUser"]       = $info["attendanceUser"] == "null" ? [] :
                json_decode($info["attendanceUser"], true);

            // 城市经理- 运营城市经理
            $info['cityManagers'] = OpenShopOrganizationManageUserModel::getData($info['id'],
                OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER);

            // 开发城市经理
            $info['developCityManagers'] = OpenShopOrganizationManageUserModel::getData($info['id'],
                OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER);

//            $info['siteSelectionDevelopments'] = OpenShopOrganizationManageUserModel::getData($info['id'],
//                OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT);

            // 门店稽核顾问
            $info['checkManagers'] = OpenShopOrganizationManageUserModel::getData(
                $info['id'], OpenShopOrganizationManageUserModel::TYPE_CHECK_MANAGER
            );

        } else {
            throw new CustomHttpResponseException(ErrCode::CODE_NO_MANAGE_DATA, null,
                ErrCode::CODE_CN[ErrCode::CODE_NO_MANAGE_DATA]);
        }
        return $info;
    }

    public static function getOrganizationList()
    {
        $list = ManageModel::getOrganizationList();
        $data = [];
        foreach ($list->toArray() as $key => $value) {
            $mappingText = '';
            if ($value['type'] == OrganizationManageEnum::TYPE_BRANCH_OFFICE) {
                foreach ($value['region_rel'] as $region) {
                    $mappingText .= $region['provinceName'] . ',';
                }
            } else {
                $mappingText = '总部';
            }
            $value['mappingText'] = trim($mappingText, ',');

            if (
                empty($value["operationAttacheUser"])
                ||
                empty($operationAttacheUser = json_decode($value["operationAttacheUser"], true))
            ) {
                $value["operationAttacheUid"] = $value["operationAttacheName"] = [];
            } else {
                $value["operationAttacheUid"]  = array_column($operationAttacheUser, "uid");
                $value["operationAttacheName"] = array_column($operationAttacheUser, "name");
            }
            unset($value["operationAttacheUser"]);
            $value["attendanceUser"]          = jsonToArr($value["attendanceUser"] ?? "", []);
            array_push($data, $value);
        }
        return $data;
    }

    public static function updateOrganizationById($manageId, $manageData, $mappingData)
    {
        //查询是否有记录
        $manageInfo = ManageModel::getManageInfo($manageId);
        if (empty($manageInfo)) {
            throw new CustomHttpResponseException(ErrCode::CODE_NO_MANAGE_DATA);
        }
        array_walk($mappingData, function (&$value, $key, $manageId) {
            $value['manageId'] = $manageId;
        }, $manageId);
        DB::beginTransaction();
        try {
            //修改基本信息
            ManageModel::query()
                       ->where('id', $manageId)
                       ->update($manageData);
            //先删除对应的mapping信息
            MappingModel::query()
                        ->where('manageId', $manageId)
                        ->update(['isDeleted' => 1]);
            //新增mapping数据
            MappingModel::query()
                        ->insert($mappingData);
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            Log::info('修改组织新信息失败' . $exception->getMessage());
            throw new CustomHttpResponseException(ErrCode::CODE_UPDATE_MANAGE_DATA);
        }
    }

    public static function getOrganizationInfoByType($type, $provinceCode = 0)
    {
        $data = [];
        if ($type == OrganizationManageEnum::TYPE_HEADQUARTERS) {
            //总部
            $data = self::getOrganizationInfoByHeadquarters();
        } elseif ($type == OrganizationManageEnum::TYPE_BRANCH_OFFICE) {
            $data = self::getOrganizationInfoByProvinceCodeCode($provinceCode);
        }
        return $data->toArray();
    }

    public static function getOrganizationInfoByProvinceCodeCode($provinceCode, $cityCode = 0, $type = 0)
    {
        //查询mapping表是否有记录
        $mappingInfo = MappingModel::query()
                                   ->where('provinceCode', $provinceCode)
                                   ->where('isDeleted', 0)
                                   ->first();
        if (empty($mappingInfo)) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_PROVINCE_NO_MANAGE));
        }
        $manageId = $mappingInfo['manageId'];

        if ($type && $provinceCode && $cityCode) {// 查询区域对应的开发城市经理
            $getManagerInfo = OrganizationManageUserService::getManagerByAddressCodes(
                OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER, $provinceCode, $cityCode
            );
            if ($getManagerInfo) {
                return (object)(['operationUid' => $getManagerInfo['userId'], 'operationName' => $getManagerInfo['name']]);
            }
        }

        //查询组织基本信息
        return ManageModel::getManageInfo($manageId);
    }

    public static function getOrganizationInfoByHeadquarters()
    {
        return ManageModel::query()
                          ->where('type', OrganizationManageEnum::TYPE_HEADQUARTERS)
                          ->where('isDeleted', 0)
                          ->first();
    }

    public static function checkProvinceIsBand($organizationId, $mapping)
    {
        foreach ($mapping as $value) {
            $first = MappingModel::query()
                                 ->where('manageId', '!=', $organizationId)
                                 ->where('provinceCode', $value['provinceCode'])
                                 ->where('isDeleted', 0)
                                 ->first();
            if ($first) {
                throw new CustomHttpResponseException(ErrCode::CODE_PROVINCE_IS_BAND, null,
                    ErrCode::CODE_CN[ErrCode::CODE_PROVINCE_IS_BAND]);
            }
        }
    }

    public static function getAreaListByUserId($userId = 0)
    {
        if (!$userId) {
            $userId = getRmsUserId();
        }
        $areaList         = OpenShopOrganizationManageModel::getOrganizationOperationListByUid($userId);
        $provinceCodeList = [];
        $isAll            = false;
        if (!empty($areaList)) {
            $areaList->each(function ($v) use (&$provinceCodeList, &$isAll) {
                if ($v->type == OrganizationManageEnum::TYPE_HEADQUARTERS) {
                    $isAll = true;
                    return false;
                }

                if (!empty($v->regionRel)) {
                    $v->regionRel->each(function ($vv) use (&$provinceCodeList) {
                        $provinceCodeList[$vv->provinceCode] = $vv->provinceCode;
                    });
                }
            });
        }


        return [
            'isAll' => $isAll,
            'list'  => array_keys($provinceCodeList)
        ];
    }


    public static function getProvinceList($userId)
    {
        $mapping = [];
        OpenShopOrganizationManageModel::query()
                                       ->where('operationUid', $userId)
                                       ->with('regionRel')
                                       ->get()
                                       ->each(function ($item) use (&$mapping) {
                                           if ($item->regionRel != null) {
                                               foreach ($item->regionRel as $value) {
                                                   $mapping[] = $value->provinceCode;
                                               }
                                           }
                                       });
        return $mapping;
    }

    /**
     * 获得省区处理人
     * @param $provinceCode
     * @param $cityCode
     * @param $type
     * @return array
     */
    public static function getProvinceInfoByProvinceCode($provinceCode, $cityCode = 0, $type = 0): array
    {
        $id = OpenShopOrganizationRegionMappingModel::query()
                                                    ->where('provinceCode', $provinceCode)
                                                    ->value('manageId');

        if ($provinceCode && $cityCode && $type) {// 查询区域对应的开发城市经理
            $getManagerInfo = OrganizationManageUserService::getManagerByAddressCodes(
                OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER, $provinceCode, $cityCode
            );
            if ($getManagerInfo) {
                return ['operationUid' => $getManagerInfo['userId'], 'type' => $type];
            }
        }

        if ($id) {
            $info = OpenShopOrganizationManageModel::query()
                                                   ->where('id', $id)
                                                   ->first();
            if (null == $info) {
                return [];
            }
            return $info->toArray();
        }
        return [];
    }


    /**
     * 获取用户组织
     *
     * @param int $uid
     * @return array|void
     * @throws Exception
     */
    public static function getUserOrganization(int $uid)
    {
        try {

            $userOrganization = OpenShopOrganizationManageModel::query()
                                                               ->where(function ($query) use ($uid) {
                                                                   $query->where("operationUid", $uid)
                                                                         ->orWhereRaw(DB::raw("JSON_CONTAINS(operationAttacheUser, JSON_OBJECT('uid', {$uid}))"));
                                                               })->get();

            return [
                "userOrganization" => $userOrganization->toArray()
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 获取用户组织
     *
     * @return array|void
     * @throws Exception
     */
    public static function organizationManageList()
    {
        try {
            $select = [
                "id",
                "name",
                "type",
                "developUid",
                "developName",
                "preparationUid",
                "preparationName",
                "designerUid",
                "designerName",
                "operationUid",
                "operationName",
                "operationAttacheUser"
            ];

            return [
                "organizationManageList" => OpenShopOrganizationManageModel::query()->with([
                    "regionRel" => function($query){
                        $query->select(["manageId", "provinceCode", "provinceName"]);
                    },
                    "managerUserRel" => function ($query) {
                        $query->whereIn("type", [
                            OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER,
                            OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER
                        ])->select(["manageId", "userId", "name", "type", "addressCodes"]);
                    }
                ])->select($select)->get()->map(function ($v) {
                    $v->operationAttacheUser = ($v->operationAttacheUser == "null" ? [] : json_decode($v->operationAttacheUser,
                        true));
                    $tempManagerUser         = $v->managerUserRel->map(function ($v) {
                        $v->addressCodes = $v->addressCodes ? json_decode($v->addressCodes, true) : [];
                        return $v;
                    })->values();

                    // 督导
                    $growManagerGroup = $tempManagerUser
                        ->where("type", OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER)
                        ->values();

                    $growManagerGroupUserIds = $growManagerGroup->pluck('userId')->toArray() ?? [];
                    if ($growManagerGroupUserIds) {
                        $shopRelData = OpenShopOrderManagerModel::getShopIdByUid($growManagerGroupUserIds);// 查询督导关联门店
                        collect($growManagerGroup)->map(
                            function ($item) use ($shopRelData) {
                                $item['shopIds'] = $shopRelData[$item['userId']] ?? [];
                                return $item;
                            }
                        );
                    }
                    $v->growManagerGroup = $growManagerGroup;

                    // 城市经理 - 运营城市经理
                    $v->cityManagerGroup     = $tempManagerUser->where("type",
                        OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER)->values();

                    // 开发城市经理
                    $v->developCityManagerGroup = $tempManagerUser->where(
                        'type',
                        OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER
                    )->values();

                    $v->provonceManagerGroup = $v->regionRel;
                    $v->offsetUnset("managerUserRel");
                    $v->offsetUnset("regionRel");
                    return $v;
                })->values(),
                "warZone" => OpenShopRegionManageModel::query()->where("status", 0)->with([
                    "regionMappingRel"     => function ($query) {
                        $query->select(["regionId", "manageId"]);
                    },
                    "regionUserMappingRel" => function ($query) {
                        $query->select(["regionId", "userId", "type"]);
                    }
                ])->select(["id", "name"])->get()->map(function (OpenShopRegionManageModel $regionManageModel) {
                    $regionManageModel->regionMapping     = $regionManageModel->regionMappingRel;
                    $regionManageModel->regionUserMapping = $regionManageModel->regionUserMappingRel;
                    $regionManageModel->offsetUnset("regionMappingRel");
                    $regionManageModel->offsetUnset("regionUserMappingRel");
                    return $regionManageModel;
                })->values()
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }
}
